
$(function () {
    var Accordion = function (el, multiple) {
        this.el = el || {};
        this.multiple = multiple || false;

        // Variables privadas
        var links = this.el.find('.link');
        // Evento
        links.on('click', { el: this.el, multiple: this.multiple }, this.dropdown)
    }

    Accordion.prototype.dropdown = function (e) {
        var $el = e.data.el;
        $this = $(this),
            $next = $this.next();

        $next.slideToggle();
        $this.parent().toggleClass('open');

        if (!e.data.multiple) {
            $el.find('.submenu').not($next).slideUp().parent().removeClass('open');
        };
    }

    var accordion = new Accordion($('#accordion'), false);
    //右侧传送
    $(function ($, window, document, undefined) {

        Slider = function (container, options) {
			/*
			options = {
				auto: true,
				time: 3000,
				event: 'hover' | 'click',
				mode: 'slide | fade',
				controller: $(),
				activeControllerCls: 'className',
				exchangeEnd: $.noop
			}
			*/

            "use strict"; //stirct mode not support by IE9-

            if (!container) return;

            var options = options || {},
                currentIndex = 0,
                cls = options.activeControllerCls,
                delay = options.delay,
                isAuto = options.auto,
                controller = options.controller,
                event = options.event,
                interval,
                slidesWrapper = container.children().first(),
                slides = slidesWrapper.children(),
                length = slides.length,
                childWidth = container.width(),
                totalWidth = childWidth * slides.length;

            function init() {
                var controlItem = controller.children();

                mode();

                event == 'hover' ? controlItem.mouseover(function () {
                    stop();
                    var index = $(this).index();

                    play(index, options.mode);
                }).mouseout(function () {
                    isAuto && autoPlay();
                }) : controlItem.click(function () {
                    stop();
                    var index = $(this).index();

                    play(index, options.mode);
                    isAuto && autoPlay();
                });

                isAuto && autoPlay();
            }

            //animate mode
            function mode() {
                var wrapper = container.children().first();

                options.mode == 'slide' ? wrapper.width(totalWidth) : wrapper.children().css({
                    'position': 'absolute',
                    'left': 0,
                    'top': 0
                })
                    .first().siblings().hide();
            }

            //auto play
            function autoPlay() {
                interval = setInterval(function () {
                    triggerPlay(currentIndex);
                }, options.time);
            }

            //trigger play
            function triggerPlay(cIndex) {
                var index;

                (cIndex == length - 1) ? index = 0 : index = cIndex + 1;
                play(index, options.mode);
            }

            //play
            function play(index, mode) {
                slidesWrapper.stop(true, true);
                slides.stop(true, true);

                mode == 'slide' ? (function () {
                    if (index > currentIndex) {
                        slidesWrapper.animate({
                            left: '-=' + Math.abs(index - currentIndex) * childWidth + 'px'
                        }, delay);
                    } else if (index < currentIndex) {
                        slidesWrapper.animate({
                            left: '+=' + Math.abs(index - currentIndex) * childWidth + 'px'
                        }, delay);
                    } else {
                        return;
                    }
                })() : (function () {
                    if (slidesWrapper.children(':visible').index() == index) return;
                    slidesWrapper.children().fadeOut(delay).eq(index).fadeIn(delay);
                })();

                try {
                    controller.children('.' + cls).removeClass(cls);
                    controller.children().eq(index).addClass(cls);
                } catch (e) { }

                currentIndex = index;

                options.exchangeEnd && typeof options.exchangeEnd == 'function' && options.exchangeEnd.call(this, currentIndex);
            }

            //stop
            function stop() {
                clearInterval(interval);
            }

            //prev frame
            function prev() {
                stop();

                currentIndex == 0 ? triggerPlay(length - 2) : triggerPlay(currentIndex - 2);

                isAuto && autoPlay();
            }

            //next frame
            function next() {
                stop();

                currentIndex == length - 1 ? triggerPlay(-1) : triggerPlay(currentIndex);

                isAuto && autoPlay();
            }

            //init
            init();

            //expose the Slider API
            return {
                prev: function () {
                    prev();
                },
                next: function () {
                    next();
                }
            }
        };

    }(jQuery, window, document));

    //轮播
    var bannerSlider = new Slider($('#banner_tabs'), {
        time: 5000,
        delay: 400,
        event: 'hover',
        auto: true,
        mode: 'fade',
        controller: $('#bannerCtrl'),
        activeControllerCls: 'active'
    });
    $('#banner_tabs .flex-prev').click(function () {
        bannerSlider.prev()
    });
    $('#banner_tabs .flex-next').click(function () {
        bannerSlider.next()
    });
    /////////送至某地////////////
    $(".dis_add").mouseenter(function () {
        $(".hide_add").css({ display: "block" })
    }).mouseleave(function () {
        $(".hide_add").css({ display: "none" })
    })
    $(".hide_add ul li a").click(function () {
        $(".hide_add").css({ display: "none" })
    })
    $(".hide_add ul li").click(function () {
        $(".hide_add ul li").find("a").removeClass("selected");
        $(this).find("a").addClass("selected");
    })
    $(".hide_add ul li a").click(function () {
        $(".hide_add").css({ display: "none" })
    })
    /////////////////////////
    $(".dao_list a").click(function () {
        $(this).addClass("color").siblings().removeClass("color")
    });
    $(".dao_list a").hover(function () {
        $('#a1').attr('src', 'http://s8.qhimg.com/share/audio/piano1/' + this.getAttribute('au') + '4.mp3');
        document.getElementById('a1').play();
    });
    /*控制显示或消失1	*/
    $(".cates").mouseenter(function () {
        var cat = $(this).attr("mt-ct");
        $(".b-" + cat + "").show().siblings().hide();
    })
    $(".important").mouseleave(function () {
        $(".import_list").hide()
    })
    /*侧边栏每块划上的时候添加颜色块*/
    $("aside ul li").mouseenter(function () {
        $(this).addClass("yanses").siblings().removeClass("yanses")
    })
    /*滚动之后固定定位*/
    $(window.document).scroll(function () {
        if ($(window).scrollTop() > 500) {
            $(".dao_hang").addClass("fixed_dh");
            $("aside").css({ display: "none" });
            $(".advertisement").css({ display: "none" });
            /*侧边栏的出现和消失*/
            $(".important").mouseenter(function () {
                $("aside").css({ display: "block", background: "#fff" })
            }).mouseleave(function () {
                $("aside").css({ display: "none" })
            })
        };
        if ($(window).scrollTop() < 500) {
            $(".dao_hang").removeClass("fixed_dh");
            $("aside").css({ display: "block" });
            $(".advertisement").css({ display: "block" });
            /*侧边栏的出现和消失*/
            $(".important").mouseleave(function () {
                $("aside").css({ display: "block" })
            })
        };
    });
    //////////////////////////////
    //点击页面移动到对应位置
    $('.fixed_position_1 ul li').click(function () {
        $('html,body').animate({ scrollTop: $('.as').eq($(this).index()).offset().top - 100 }, 500);
    }
    );
    //滚动条移动到对应的位置，对应的标签高亮显示
    $(window.document).scroll(function () {
        for (var i = 0; i < $(".as").length; i++) {
            if ($(window).scrollTop() > $(".as").eq(i).offset().top - 300) {
                $(".fixed_position_1 ul li").eq(i).addClass("addcss").siblings(".fixed_position_1 ul li").removeClass("addcss");
            }
        };
    });
    //楼层的出现或消失
    $(window.document).scroll(function () {
        if ($(window).scrollTop() > 500) {
            $(".fixed_position_1").css({ display: "block" })

        };
        if ($(window).scrollTop() < 500) {
            $(".fixed_position_1").css({ display: "none" })

        };
    });


    var i = 0
    var clone = $(".lunbobanner .lunboimg li").first().clone();
    $(".lunbobanner .lunboimg").append(clone)
    var size = $(".lunbobanner .lunboimg li").size()
    /*自动轮播*/
    var t = setInterval(moveL, 5000)
    /*定时器的关闭与开启*/
    $(".kongzhianniu").hover(function () {
        clearInterval(t);

    }, function () {
        t = setInterval(moveL, 5000)

    })

    $(".btnr").click(function () {
        moveL()
    })
    function moveL() {
        i++
        if (i == size) {
            $(".lunboimg").css({ left: 0 })
            i = 1;
        }
        $(".lunboimg").stop().animate({ left: -i * 1200 }, 500)
    }

    $(".btnl").click(function () {
        moveR()
    })
    function moveR() {
        i--
        if (i == -1) {
            $(".lunboimg").css({ left: -(size - 1) * 1200 })
            i = size - 2;
        }
        $(".lunboimg").stop().animate({ left: -i * 1200 }, 500)
    }
    /////////////////////////////////
    var offset = $(".toolbar-item-weixin").offset();
    //加入购物车
    $(".add_scar").click(function (event) {
        var addcar = $(this);
        var img = addcar.parent().parent().find('img').attr('src') || '/images/word-img/gerj1.jpg';
        var flyer = $('<img class="u-flyer" src="' + img + '">');
        var tops = $(window).scrollTop()

        flyer.fly({
            start: {
                left: event.pageX, //开始位置（必填）#fly元素会被设置成position: fixed 
                top: event.pageY - tops, //开始位置（必填）
                width: 0, //结束时宽度 
                height: 0 //结束时高度  
            },
            end: {
                left: offset.left, //结束位置（必填） 
                top: offset.top + 40, //结束位置（必填） 
                width: 0, //结束时宽度 
                height: 0 //结束时高度 
            },

        });
    });
})
//热门最新切换
$('.newHot').click(function () {
    index = $(this).index();
    if (index == 0) {
        $('#newHot1').addClass('color')
        $('#newHot2').removeClass('color2')
        $('#notice_new2').fadeOut('slow', function () {
            $('#notice_new1').fadeIn()
        })
    } else {
        $('#newHot2').addClass('color2')
        $('#newHot1').removeClass('color')
        $('#notice_new1').fadeOut('slow', function () {
            $('#notice_new2').fadeIn()
        })
    }
})

//加入购物车
function join(id, event) {
    $.post('/shopCar/join/' + id, {}, function (data) {
        if (data.status == 1) {
            layer.msg(data.msg)
            $('#myCar').html('<span id="myCar">我的购物车<span class="color2">( ' + data.num + ' )</span></span>');
        } else {
            layer.msg('请登录后再使用购物车功能')
        }
    })
}
//收藏
function shoucang(id) {
    $.post('/shopCar/shoucang/' + id, {}, function (data) {
        if (data.status == 1) {
            layer.msg(data.msg)
        } else {
            layer.msg('请登录后再使用收藏功能')
        }
    })
}
/*首页各个书籍(作者)分类选项卡*/
function queryBook(id, j) {
    $.post('/bookList/' + id, {}, function (data) {
        if (data.status == 1) {
            var html = ''
            for (var i = 0; i < data.result.length; i++) {
                html += '<li>';
                html += '<a href="/bookDetil/?id=' + data.result[i]._id + '"><img src="images/books/' + data.result[i].img + '" style="margin:0 auto;display:block;width:220px;height:220px"></a>';
                html += '<light1><img src="images/saoguang.png"></light1>';
                html += '<a href="#"><p>' + data.result[i].name + '</p><p style="margin-left:12px">' + data.result[i].author_id.name + '</p></a>';
                html += ' <span>￥' + data.result[i].money + '</span>';
                html += '<em><a href="javascript:;" onclick="shoucang(\'' + data.result[i]._id + '\')">收藏</a><a href="javascript:;" class="add_scar" onclick="join(\'' + data.result[i]._id + '\')">加入购物车</a></em>';
                html += '</li>';
            }
            $('#' + 'indexBook_list_' + j).html('')
            $('#' + 'indexBook_list_' + j).html(html)
        } else {
            layer.msg(data.msg)
        }
    })
}
/*添加色块*/
$(".detailed_navigation ul li").click(function () {
    $(this).addClass("yadi").siblings().removeClass("yadi")
})


$('.headerList').mouseover(function () {
    var index = $(this).index()
    $('.headerBookList').eq(index).show().siblings().hide()
})

function colmunName(id) {
    $('.link').removeClass('nav_color')
    $.post('/classify/book_list', { id: id }, function (data) {
        if (data.status == 1) {
            var html = '';
            for (var i = 0; i < data.author.length; i++) {
                html += '<li><a href="javascript:;" onclick="author_list_book(\'' + data.author[i]._id+'\')">' + data.author[i].name + '</a></li>';
            }
            $('.submenu').html('');
            $('.submenu').html(html);
            var html2 = '';
            html2 += '<div class="container-fluid book_list"><div class="row">';
            for (var i = 0; i < data.result.length; i++) {
                html2 += '<div class="col-xs-6 col-md-3">';
                html2 += '<ul class="list-group book_list2">';
                html2 += '<li class="list-group-item">';
                html2 += '<a href="/bookDetil/?id='+data.result[i]._id+'"><img src="images/books/'+data.result[i].img+'" style="width:160px;height:160px;"></a>';
                html2 += '<span class="topKuang">';
                html2 += '<a href="javascript:void(0)" onclick="shoucang(\'' + data.result[i]._id+ '\')">收藏</a>';
                html2 += '<a href="javascript:void(0)" class="add_scar" onclick="join(\'' + data.result[i]._id + '\')">加入购物车</a>';
                html2 += '</span>';
                html2 += '</li>';
                html2 += '<li class="list-group-item" style="line-height:12px;max-height:75px">';
                html2 += '<p>' + data.result[i].name +'</p>';
                html2 += '<p class="text-muted" style="margin-left:10px">'+data.result[i].author_id.name+'</p>';
                html2 += '<p class="color text-right" style="font-size:18px">￥'+data.result[i].money+'</p>';
                html2 += '</li></ul></div>';
                html2 += '';
                html2 += '';
            }
            html2 += '</div></div>';
            $('#book_list').html('');
            $('#book_list').html(html2);
        }
    })
}
function author_list_book(id) {
    $.post('/classify/author_list_book',{id:id},function(data) {
        if (data.status == 1) {
            var html2 = '';
            html2 += '<div class="container-fluid book_list"><div class="row">';
            for (var i = 0; i < data.result.length; i++) {
                html2 += '<div class="col-xs-6 col-md-3">';
                html2 += '<ul class="list-group book_list2">';
                html2 += '<li class="list-group-item">';
                html2 += '<a href="/bookDetil/?id=' + data.result[i]._id + '"><img src="images/books/' + data.result[i].img + '" style="width:160px;height:160px;"></a>';
                html2 += '<span class="topKuang">';
                html2 += '<a href="javascript:void(0)" onclick="shoucang(\'' + data.result[i]._id + '\')">收藏</a>';
                html2 += '<a href="javascript:void(0)" class="add_scar" onclick="join(\'' + data.result[i]._id + '\')">加入购物车</a>';
                html2 += '</span>';
                html2 += '</li>';
                html2 += '<li class="list-group-item" style="line-height:12px;max-height:75px">';
                html2 += '<p>' + data.result[i].name + '</p>';
                html2 += '<p class="text-muted" style="margin-left:10px">' + data.result[i].author_id.name + '</p>';
                html2 += '<p class="color text-right" style="font-size:18px">￥' + data.result[i].money + '</p>';
                html2 += '</li></ul></div>';
                html2 += '';
                html2 += '';
            }
            html2 += '</div></div>';
            $('#book_list').html('');
            $('#book_list').html(html2);
        }
    })
}


$.fn.GL = function (options) {
    var dataop = {
        ocolor: 'red',
        oshuru: '高亮',
    };
    var chuancan = $.extend(dataop, options);
    $(this).each(function ()//先遍历，清除上一次的样式
    {
        var _this = $(this)
        _this.find($(".glnow")).each(function ()//找到所有highlight属性的元素；
        {
            $(this).css({ color: "" });//将他们的属性去掉；
        });
    });
    if (chuancan.oshuru == '') {
        return false;
    } else {
        var regExp = new RegExp("(" + chuancan.oshuru.replace(/[(){}.+*?^$|\\\[\]]/g, "\\$&") + ")", "ig");//创建正则表达式，g表示全局的，如果不用g，则查找到第一个就不会继续向下查找了；
        $(this).each(function ()//遍历文章；
        {
            var _this1 = $(this)
            var html = _this1.html();
            var newHtml = html.replace(regExp, '<span class="glnow" style="color:' + chuancan.ocolor + '">' + chuancan.oshuru + '</span>');//将找到的关键字替换，加上highlight属性；
            _this1.html(newHtml);//更新文章；
        });
    }
}
$('.user').blur(function () {
    
})
$('.denglu').click(function() {
    $('.denglu').addClass('activ')
    $('.zhuce').removeClass('activ')
    $('.lDiv').fadeIn()
    $('.zDiv').fadeOut()
})
$('.zhuce').click(function() {
    $('.zhuce').addClass('activ')
    $('.denglu').removeClass('activ')
    $('.zDiv').fadeIn()
    $('.lDiv').fadeOut()
})